/**
 * @author:稀饭
 * @time:下午11:59:24
 * @filename:CreateVideo.java
 */
package service;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.text.NumberFormat;
import java.util.concurrent.ThreadPoolExecutor;

import dao.Video;

public class CreateVideo implements Runnable, Create {
	private Video video;
	private ThreadPoolExecutor threadPool;

	public void setThreadPool(ThreadPoolExecutor threadPool) {
		this.threadPool = threadPool;
	}

	public void setVideo(Video video) {
		this.video = video;
	}

	public void run() {
		downLoadFromUrl(video);
	}

	@Override
	public void downLoadFromUrl(Video video) {
		// TODO Auto-generated method stub
		ConnectionWork connectionWork = new ConnectionWork();
		String savePath = video.getPath();
		String fileName = video.getName();
		String urlStr = video.getUrl();
		String referString = video.getReferString();
		File file = new File(savePath + fileName);
		// 开启代理
		// int rand = (int) (Math.random() * 100) % 5;
		// System.setProperty("http.proxyHost",dataClass.proxyIp[rand]);
		// System.setProperty("http.proxyPort",dataClass.proxyPort[rand]);
		// 文件不存在才进行下载
		long size = 0;
		// 得到输入流
		InputStream inputStream = null;
		HttpURLConnection conn = null;
		conn = connectionWork.getConn(urlStr, referString);
		try {
			inputStream = conn.getInputStream();
		} catch (IOException e) {
			// TODO Auto-generated catch block
//			e.printStackTrace();
		}
		// 获取待上传的文件大小
		size = conn.getContentLength();
		if (file.exists()) {
			if (size > file.length()) {
				file.delete();
				if(inputStream!=null)
					upload(inputStream, file, fileName, size);
			} else {
				System.out.println(fileName + "已存在文件夹中，无须下载，且大小为"
						+ file.length() + "，系统文件大小为" + size);
			}
		} else {
			if(inputStream!=null)
				upload(inputStream, file, fileName, size);
		}
	}

	public void upload(InputStream inputStream, File file, String fileName,
			long size) {
		long alreadySize = 0;
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(file);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
//			e.printStackTrace();
		}
		byte[] temp = new byte[1024];
		int len;
		try {
			while ((len = inputStream.read(temp)) != -1) {

				fos.write(temp, 0, len);
				alreadySize += len;
				System.out
						.println("此刻激活的线程有：" + threadPool.getActiveCount()
								+ "，此刻在队列中等待的线程有："
								+ threadPool.getQueue().size()
								+ "，此刻已经完成使命的线程有："
								+ threadPool.getCompletedTaskCount());
				System.out.println(fileName + ",总共" + size + ",已下载"
						+ alreadySize);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
//			e.printStackTrace();
		}
		System.out.println(fileName + "已下载完成");
		try {
			fos.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
//			e.printStackTrace();
		}
		try {
			inputStream.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
//			e.printStackTrace();
		}
	}

	/**
	 * 获取完成度
	 * 
	 * @param p1
	 * @param p2
	 * @return
	 */
	@Override
	public String percent(double p1, double p2) {
		String str;
		double p3 = p2 / p1;
		NumberFormat nf = NumberFormat.getPercentInstance();
		nf.setMaximumFractionDigits(0);
		str = nf.format(p3);
		return str;
	}
}
